﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RaygunDiplomacy.Model.Terrain.Local
{

   public static class CellArrayExtensions
   {
      public static Cell[,] GetSheetForRow(this Cell[, ,] cells, int row)
      {
         int columns = cells.GetLength(1);
         int layers = cells.GetLength(2);

         Cell[,] sheet = new Cell[columns, layers];

         for (int i = 0; i < columns; i++)
         {
            for (int j = 0; j < layers; j++)
            {
               sheet[i, j] = cells[row, i, j];
            }
         }

         return sheet;
      }
   }

   public class ChunkCells
   {
      public const int ChunkSize = 32;
      public static readonly SpatialIndex MaxIndex = new SpatialIndex(ChunkSize, ChunkSize, ChunkSize);

      int airCells = ChunkSize * ChunkSize * ChunkSize;

      Lazy<Cell[, ,]> cells = new Lazy<Cell[, ,]>(() => new Cell[ChunkSize, ChunkSize, ChunkSize]);

      public Cell this[SpatialIndex index]
      {
         get
         {
            if (cells.IsValueCreated)
            {
               return cells.Value[index.Row, index.Column, index.Layer];
            }
            return null;
         }
         set
         {
            if (Cell.IsNullOrAir(value) && !cells.IsValueCreated)
            {
               return;
            }

            if (index.OutOfRange(cells.Value))
            {
               throw new IndexOutOfRangeException();
            }

            if (Cell.IsNullOrAir(value) != Cell.IsNullOrAir(cells.Value[index.Row, index.Column, index.Layer]))
            {
               if (Cell.IsNullOrAir(value))
               {
                  airCells++;

                  if (airCells == ChunkSize * ChunkSize * ChunkSize)
                  {
                     cells = new Lazy<Cell[, ,]>(() => new Cell[ChunkSize, ChunkSize, ChunkSize]);
                  }
               }
               else
               {
                  airCells--;
               }
            }

            cells.Value[index.Row, index.Column, index.Layer] = value;
         }
      }
   }
}
